/**
 * 
 */

package com.example.android.myapp.asyn;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;

import org.apache.http.HttpStatus;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

/**
 * @author Lifeix
 * 
 */
public abstract class SogouHttpTask<T> extends DialogTask<Bundle, Void, BetterHttpResponse> {
    protected final String   TAG;
    
    private static final int HTTP_UNKNOWN = 0;
    
    public static final int  HTTP_GET     = 1;
    
    public static final int  HTTP_POST    = 2;

    private Class<T>         mTcls;
    
    private boolean          mShowDialog;
    
    private boolean          mCancelable;
    
    private int              mHttpType    = HTTP_UNKNOWN;
    
    private String           mRequestURL;
    
    
    public SogouHttpTask(Activity context) {
        this(context, true, true);
    }
    
    @SuppressWarnings("unchecked")
    public SogouHttpTask(Activity context, boolean showdialog, boolean cancelable) {
        super(context, showdialog, cancelable);
        TAG = getClass().getSimpleName();
        mTcls = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
    
    public boolean isShowDialog() {
        return mShowDialog;
    }
    
    public void setShowDialog(boolean showdialog) {
        mShowDialog = showdialog;
    }
    
    public boolean isCancelable() {
        return mCancelable;
    }
    
    public void setCancelable(boolean cancelable) {
        mCancelable = cancelable;
    }
    
    public void setRequestURL(String requesturl) {
        mRequestURL = requesturl;
    }
    
    public String getRequestURL() {
        return mRequestURL;
    }
    
    public void setHttpType(int type) {
        mHttpType = type;
    }
    
    public int getHttpType() {
        return mHttpType;
    }
    
    public SogouHttpTask<T> execute(String url, int type, Bundle parames) {
        mRequestURL = url;
        mHttpType = type;
        super.execute(parames);
        return this;
    }
    
    @Override
    protected void before(Context context) {
        super.before(context);
        setMessage("正在获取数据，请稍后。。。。");
    }
    
    protected BetterHttpResponse doCheckedInBackground(Context context, Bundle... params) throws Exception {
        super.doCheckedInBackground(context, params);
        if (HTTP_UNKNOWN == mHttpType) {
            throw new IllegalArgumentException("You should set the http request type(HTTP_GET or HTTP_POST) before "
                    + "call execute(Params... params)");
        }
        
        if (null == mRequestURL) {
            throw new NullPointerException("The request url can not be null, you should set the http request URL "
                    + "before call execute(Params... params)");
        }
        
        Bundle bundle = params[0];
        BetterHttpResponse response = null;
        if (HTTP_GET == mHttpType) {
//                response = A06Client.httpGetRequest(mRequestURL, bundle);
		} else if (HTTP_POST == mHttpType) {
//                response = A06Client.httpPostRequest(mRequestURL, bundle);
		}
        return response;
    }
    
    @Override
    protected void after(Context context, BetterHttpResponse result) {
        super.after(context, result);
        if (null != result) {
            if (HttpStatus.SC_OK == result.getStatusCode()) {
                try {
                    String str = result.getResponseBodyAsString();
//                    T responseBean = s_json.fromJson(mTcls, str);
//                    T responseBean = new Gson().fromJson(str, mTcls);
//                    if (ResponseCodes.SUCCESS_STATUS.getCode() == responseBean.getCode()) {
//                        // 应用“Change”到GameMainActivity
//                        ResponseChangeBean change = responseBean.getChange();
//                        if (null != change) {
//                            if (context instanceof GameMainActivity) {
//                                GameMainActivity main = (GameMainActivity) context;
//                                main.handlePlayerInfoChanged(change);
//                            } else {
//                                Log.d(getClass().getSimpleName(), "The change has not been apply.");
//                            }
//                        } else {
//                            Log.d(getClass().getSimpleName(), "The change is null.");
//                        }
//                        
//                        // 处理OK的Result
//                        handleOkResult(responseBean);
//                    } else {
//                        handleCommonBadResult(context, responseBean);
//                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    handleException(context, e);
                }
            } else {
                handleBadHttpStatus(context, result.getStatusCode());
            }
        } else {
            handleNullResult(context);
        }
    };
    
    public void handleNullResult(Context context) {
//        ((Activity) context).showDialog(NetTaskDialogFactory.DIALOG_HTTPRESPONSE_NULL);
    }
    
    public void handleBadHttpStatus(Context context, int status) {
//        ((Activity) context).showDialog(NetTaskDialogFactory.DIALOG_HTTPRESPONSE_NULL);
    }
    
    @Override
    protected void handleError(Context context, Exception error) {
        handleException(context, error);
    }
    
    public void handleException(Context context, Exception e) {
//        ((Activity) context).showDialog(NetTaskDialogFactory.DIALOG_HTTPRESPONSE_EXCEPTION);
    }
    
    private final void handleCommonBadResult(Context context, T result) {
//        if (ResponseCodes.MULTIPLE_SIGNIN.getCode() == result.getCode()) {
//            Intent data = new Intent();
//            data.putExtra("multiple_signin", true);
//            ((Activity) context).setResult(Activity.RESULT_CANCELED, data);
//            ((Activity) context).finish();
//        } else if (ResponseCodes.UNKNOWN_ERROR.getCode() == result.getCode()) {
//            ((Activity) context).showDialog(NetTaskDialogFactory.DIALOG_BASERESULT_UNKNOWN_ERROR);
//        }
        
        handleBadResult(result);
    }
    
    public void handleBadResult(T result) {
    }
    
    public abstract void handleOkResult(T result);
}
